import ColorThief from 'colorthief'
import type { MyItemWidthProps } from '../type'

/**
 * @description: 获取当前窗口尺寸下格子的宽度
 * @param {ItemWidthProps} param1
 * @return {*}
 */
export const getItemWidth = ({
  breakpoints,
  wrapperWidth,
  gutter,
  hasAroundGutter,
  initWidth
}: MyItemWidthProps) => {
  // 获取升序尺寸集合
  const sizeList: number[] = Object.keys(breakpoints)
    .map(key => {
      return Number(key)
    })
    .sort((a, b) => a - b)

  // 获取当前的可用宽度
  let validSize = wrapperWidth
  let breakpoint = false
  for (const size of sizeList) {
    if (wrapperWidth <= size) {
      validSize = size
      breakpoint = true
      break
    }
  }

  // 非断点，返回设置的宽度
  if (!breakpoint) return initWidth

  // 断点模式，计算当前断点下的宽度
  let breakWidth = 0
  const col = breakpoints[validSize]!.rowPerView
  if (hasAroundGutter) breakWidth = (wrapperWidth - gutter) / col - gutter
  else breakWidth = (wrapperWidth - (col - 1) * gutter) / col

  return Math.floor(breakWidth)
}

export const loadImage = (url: string, crossOrigin = true): Promise<HTMLImageElement> => {
  return new Promise((resolve, reject) => {
    // const img = document.createElement('img')
    // if (crossOrigin) img.crossOrigin = 'Anonymous'

    // img.onload = () => {
    //   resolve(img)
    // }
    // img.onerror = () => {
    //   reject(new Error('Image load error'))
    // }
    // img.src = url

    const image = new Image()
    image.onload = () => {
      resolve(image)
    }
    image.onerror = () => {
      reject(new Error('Image load error'))
    }
    if (crossOrigin) image.crossOrigin = 'Anonymous' // 支持跨域图片

    image.src = url
  })
}

export const calculateDominantColor = async (img: HTMLImageElement) => {
  return new Promise(resolve => {
    const colorThief = new ColorThief()

    if (img.complete) {
      const [r, g, b] = colorThief.getColor(img)
      // console.log('result', [r, g, b])

      const palette = colorThief.getPalette(img, 3)
      console.log('palette', palette)

      resolve({ r, g, b })
    } else {
      img.addEventListener('load', () => {
        const [r, g, b] = colorThief.getColor(img)
        resolve({ r, g, b })
      })
    }
  })

  // const canvas = document.createElement('canvas')
  // const ctx = canvas.getContext('2d')

  // // 使用1x1像素的canvas获取平均色
  // canvas.width = 1
  // canvas.height = 1
  // ctx.drawImage(img, 0, 0, 1, 1)
  // const [r, g, b] = ctx.getImageData(0, 0, 1, 1).data

  // return { r, g, b }
}

export const getBottomDominantColor = async (img: HTMLImageElement, height = 5) => {
  return new Promise((resolve, reject) => {
    const canvas = document.createElement('canvas') as HTMLCanvasElement
    const ctx = canvas.getContext('2d')

    canvas.width = img.naturalWidth
    canvas.height = Math.min(height, img.naturalHeight)

    if (!ctx) {
      reject(new Error('Canvas context is null'))
      return
    }
    ctx.drawImage(
      img,
      0,
      img.naturalHeight - canvas.height, // 从图片底部开始
      img.naturalWidth,
      canvas.height, // 截取的区域宽高
      0,
      0, // 在Canvas上放置的位置
      img.naturalWidth,
      canvas.height // 在Canvas上绘制的宽高
    )

    const a = true
    if (a) {
      const colorThief = new ColorThief()
      const dataURL = canvas.toDataURL('image/png')
      const bottomImg = document.createElement('img')
      bottomImg.onload = () => {
        const [r, g, b] = colorThief.getColor(bottomImg)
        resolve({ r, g, b })
      }
      bottomImg.src = dataURL
      // colorThief.getColorAsync(dataURL, ([r, g, b]) => {
      //   resolve({ r, g, b })
      // })
    } else {
      const [r, g, b] = ctx.getImageData(0, 0, canvas.width, canvas.height).data
      resolve({ r, g, b })
    }
  })
}
